<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="78%">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px" v-loading="formLoading">
      <!-- 基本信息 -->
      <el-card class="box-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>基本信息</span>
          </div>
        </template>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="保养单号">
              <span class="info-value">{{ taskDetail.code || '-' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="图号">
              <span class="info-value">{{ taskDetail.drawingNo || '-' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="模具名">
              <span class="info-value">{{ taskDetail.accountName || '-' }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="模具编码">
              <span class="info-value">{{ taskDetail.accountCode || '-' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="指派人">
              <span class="info-value">{{ taskDetail.assigneerName || '-' }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 报工信息 -->
      <el-card class="box-card mt-20" shadow="never">
        <template #header>
          <div class="card-header">
            <span>报工信息</span>
          </div>
        </template>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="保养分类">
              <span class="info-value">{{ taskDetail.upkeepCategory || '-' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="保养人员">
              <span class="info-value">{{ formatRepairers(taskDetail.assigneerIds) || '-' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="任务接收时间">
              <span class="info-value">{{ formatTime(taskDetail.taskReceiveTime) }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="任务开始时间">
              <span class="info-value">{{ formatTime(taskDetail.taskStartTime) }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="任务结束时间">
              <span class="info-value">{{ formatTime(taskDetail.taskEndTime) }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="理论保养工时">
              <span class="info-value">{{ taskDetail.taskExecutionDuration || '-' }} 分钟</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="实际开始时间" prop="actualStartTime">
              <el-date-picker v-model="formData.actualStartTime" type="datetime" placeholder="选择实际开始时间" value-format="x"
                style="width: 100%" @change="calculateDuration" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="实际结束时间" prop="actualEndTime">
              <el-date-picker v-model="formData.actualEndTime" type="datetime" placeholder="选择实际结束时间" value-format="x"
                style="width: 100%" @change="calculateDuration" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="实际保养工时">
              <el-input v-model="formData.actualExecutionDuration" placeholder="自动计算" readonly class="readonly-input">
                <template #append>分钟</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="审核描述" prop="auditDescription">
              <el-input v-model="formData.auditDescription" type="textarea" :rows="3" placeholder="请输入审核描述" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 保养项目列表 -->
      <el-card class="box-card mt-20" shadow="never">
        <template #header>
          <div class="card-header" style="display: flex; justify-content: space-between; align-items: center;">
            <span>保养项目列表</span>
            <div style="display: flex; align-items: center;">
              <span class="completed-count">已完成 {{ completedItemsCount }} / {{ items.length }} 项</span>
              <el-checkbox v-model="formData.isCompleted" @change="handleCompletedChange" style="margin-left: 15px;">
                工单已完成
              </el-checkbox>
            </div>
          </div>
        </template>

        <el-table :data="items" class="items-table" border
          :header-cell-style="{ background: '#e6f7ef', color: '#008c46' }">
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column label="保养项目名称" prop="itemName" min-width="150" />
          <el-table-column label="保养项目编码" prop="itemCode" width="120" />
          <el-table-column label="描述" min-width="200">
            <template #default="scope">
              <div class="rich-text-content" v-html="scope.row.itemDescription || '-'"></div>
            </template>
          </el-table-column>
          <el-table-column label="是否完成" width="100" align="center">
            <template #default="scope">
              <el-checkbox v-model="scope.row.isCompleted" @change="handleItemCompleteChange(scope.row)" />
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-form>

    <template #footer>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button @click="handleCancelWorkReport" type="warning">撤销报工</el-button>
      <el-button @click="submitAudit" type="primary" :disabled="formLoading">审 核</el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, watch, computed } from 'vue'
import * as UserApi from '@/api/system/user'
import type { UserVO } from '@/api/system/user'
import { DICT_TYPE } from '@/utils/dict'
import { dayjs } from 'element-plus'
import { UpkeepTobeApi } from '@/api/mold/upkeeptobe'
import { UpkeepTaskApi, UpkeepTaskModStautus } from '@/api/mold/upkeeptask'
import { useMessage } from '@/hooks/web/useMessage'
import { UpkeepItemApi } from '@/api/mold/upkeepitem'

const { success, error } = useMessage() // 消息弹窗

const dialogTitle = ref('审核')
const dialogVisible = ref(false)
const formLoading = ref(false)
const formRef = ref()
const currentId = ref<number | undefined>(undefined)
const currentTaskId = ref<number | undefined>(undefined)
const tobeDetail = ref({}) // 存储tobe详情
const taskDetail = ref({}) // 存储task详情
const items = ref([]) // 存储工单项详情

// 表单数据
const formData = reactive({
  id: undefined as number | undefined, // task ID
  repairerIds: [] as number[], // 保养人员IDs
  actualStartTime: undefined as number | undefined, // 实际开始时间
  actualEndTime: undefined as number | undefined, // 实际结束时间
  actualExecutionDuration: undefined as number | undefined, // 实际保养工时
  auditDescription: '' as string, // 审核描述
  items: [] as any[], // 保养项目IDs
  isCompleted: false as boolean // 工单是否完成
})

const message = useMessage() // 消息弹窗
const userList = ref<UserVO[]>([]) // 用户列表

// 计算已完成的保养项数量
const completedItemsCount = computed(() => {
  return items.value.filter(item => item.isCompleted).length
})

// 表单校验规则
const formRules = {
  actualStartTime: [
    { required: true, message: '实际开始时间不能为空', trigger: 'change' }
  ],
  actualEndTime: [
    { required: true, message: '实际结束时间不能为空', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (formData.actualStartTime && value <= formData.actualStartTime) {
          callback(new Error('实际结束时间必须晚于开始时间'));
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ]
}

// 打开弹窗
const open = async (id: number, taskId: number) => {
  dialogVisible.value = true
  dialogTitle.value = '审核'

  // 重置表单
  Object.assign(formData, {
    id: undefined,
    repairerIds: [],
    actualStartTime: undefined,
    actualEndTime: undefined,
    actualExecutionDuration: undefined,
    auditDescription: '',
    items: [],
    isCompleted: false
  })

  currentId.value = id
  currentTaskId.value = taskId

  await Promise.all([
    getUserList(),
    getUpkeepTobe(id),
    getUpkeepTask(taskId),
    getItemsOfTask(taskId)
  ])

  formLoading.value = false
}

// 提交审核
const emit = defineEmits(['success'])
const submitAudit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid: boolean) => {
    if (!valid) return

    try {
      formLoading.value = true

      // 准备保养项数据
      const upkeepItems = items.value.map(item => ({
        taskId: currentTaskId.value,
        itemId: item.itemId,
        isCompleted: item.isCompleted ? 1 : 0
      }))

      // 调用审核接口
      await UpkeepTobeApi.auditUpkeepTobe({
        id: formData.id,
        assigneerIds: formData.repairerIds,
        actualStartTime: formData.actualStartTime,
        actualEndTime: formData.actualEndTime,
        actualExecutionDuration: formData.actualExecutionDuration,
        auditDescription: formData.auditDescription,
        upkeepItems: upkeepItems
      })

      success('审核成功')
      dialogVisible.value = false
      emit('success')
    } catch (err) {
      error('审核失败: ' + (err?.message || '未知错误'))
      console.error(err)
    } finally {
      formLoading.value = false
    }
  })
}

// 暴露方法给父组件使用
defineExpose({ open })

/** 获取用户列表 */
const getUserList = async () => {
  try {
    userList.value = await UserApi.getSimpleUserList()
  } catch (error) {
    message.error('获取用户列表失败')
    console.error(error)
  }
}

/** 获取申请单详情 */
const getUpkeepTobe = async (id: number) => {
  try {
    const data = await UpkeepTobeApi.getUpkeepTobe(id)
    tobeDetail.value = data
  } catch (error) {
    message.error('获取审核信息失败')
    console.error(error)
  }
}

/** 获取工单详情 */
const getUpkeepTask = async (id: number) => {
  try {
    const data = await UpkeepTaskApi.getUpkeepTask(id)
    taskDetail.value = data

    // 填充表单数据
    Object.assign(formData, {
      id: data.id,
      repairerIds: data.repairerIds || [],
      actualStartTime: data.actualStartTime,
      actualEndTime: data.actualEndTime,
      actualExecutionDuration: data.actualExecutionDuration,
      auditDescription: data.auditDescription || ''
    })
  } catch (error) {
    message.error('获取审核信息失败')
    console.error(error)
  }
}

/** 获取工单详情 */
const getItemsOfTask = async (id: number) => {
  try {
    const data = await UpkeepItemApi.getItemsOfTask(id)
    // 转换isCompleted为布尔值
    items.value = data.map(item => ({
      ...item,
      isCompleted: !!item.isCompleted
    }))

    // 设置工单完成状态
    formData.isCompleted = items.value.every(item => item.isCompleted)
  } catch (error) {
    message.error('获取审核信息失败')
    console.error(error)
  }
}

/** 格式化保养人员显示 */
const formatRepairers = (repairerIds: number[]) => {
  if (!repairerIds || !userList.value.length) return '-'

  return repairerIds.map(id => {
    const user = userList.value.find(user => user.id === id)
    return user ? user.nickname : `未知用户(${id})`
  }).join('、')
}

/** 计算实际保养工时（以分钟为单位） */
const calculateDuration = () => {
  const start = formData.actualStartTime
  const end = formData.actualEndTime

  if (!start || !end) {
    formData.actualExecutionDuration = undefined
    return
  }

  // 确保结束时间晚于开始时间
  if (end <= start) {
    formData.actualExecutionDuration = 0
    return
  }

  // 计算分钟数
  const duration = (end - start) / (1000 * 60)
  formData.actualExecutionDuration = Math.floor(duration)
}

/** 格式化时间戳 */
const formatTime = (timestamp: number | string | Date) => {
  if (!timestamp) return '-'
  // 如果是字符串或数字形式的时间戳，转换为数字
  const ts = typeof timestamp === 'string' ? parseInt(timestamp) : timestamp
  return dayjs(ts).format('YYYY-MM-DD HH:mm:ss')
}

/** 撤销报工 */
const handleCancelWorkReport = async () => {
  if (!formData.id) {
    message.error('无效的任务ID')
    return
  }
  const upkeepTaskModStautus: UpkeepTaskModStautus = {
    id: formData.id,
    status: 3 // 设置状态为"保养中",
  }

  var f = await UpkeepTaskApi.modStatus(upkeepTaskModStautus)

  if (!f) {
    message.error('撤销报工失败')
    return
  }

  message.success('撤销成功')
  dialogVisible.value = false

  // 触发成功事件，让父组件刷新列表
  emit('success')
}

// 处理工单完成状态变化
const handleCompletedChange = (checked: boolean) => {
  if (checked) {
    // 如果勾选了"工单已完成"，则所有保养项都标记为完成
    items.value.forEach(item => {
      item.isCompleted = true
    })
  } else {
    // 如果取消勾选"工单已完成"，则所有保养项都标记为未完成
    items.value.forEach(item => {
      item.isCompleted = false
    })
  }
}

// 处理单个保养项完成状态变化
const handleItemCompleteChange = (item: any) => {
  // 如果某个保养项未完成，则工单不能标记为完成
  if (!item.isCompleted) {
    formData.isCompleted = false
  } else {
    // 如果所有保养项都完成了，自动勾选工单完成
    formData.isCompleted = items.value.every(i => i.isCompleted)
  }
}

// 监听时间变化，自动计算工时
watch([() => formData.actualStartTime, () => formData.actualEndTime], () => {
  calculateDuration()
})
</script>

<style scoped>
.mt-20 {
  margin-top: 20px;
}

.rich-text-content {
  line-height: 1.6;
}

.info-value {
  color: #303133;
  font-weight: 400;
}

.readonly-input {
  background-color: #f5f7fa;
}

.items-table {
  width: 100%;
  margin-top: 15px;
}

.status-completed {
  color: #67c23a;
}

.status-pending {
  color: #e6a23c;
}

.completed-count {
  font-size: 14px;
  color: #606266;
  margin-right: 10px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>